package org.ttitfly.workflow.spring;

import java.io.File;
import java.net.URL;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.ttitfly.workflow.engine.ProcessFactory;
import org.ttitfly.workflow.engine.basic.XMLProcessFactory;
import org.ttitfly.workflow.factory.DefaultObjectFactory;
import org.ttitfly.workflow.factory.ObjectFactory;


/**
 * spring 的SessionEstablishmentFactoryBean
 * 
 * @author 潘海春
 * @version 2011-3-5
 */
public class ProcessFactoryBean implements FactoryBean<ProcessFactory>, BeanFactoryAware, InitializingBean {

	/** 流程定义配置文件地址，如果注入了processFactory则不会被用到 */
	private Resource processLocations;

	/** spring bean factory，如果注入了processFactory则不会被用到 */
	private BeanFactory beanFactory;
	
	private ProcessFactory processFactory;

	public void setProcessLocations(Resource processLocations) {
		this.processLocations = processLocations;
	}

	@Override
	public ProcessFactory getObject() throws Exception {
		return processFactory;
	}

	@Override
	public Class<?> getObjectType() {
		return processFactory != null ? processFactory.getClass() : ProcessFactory.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		File processdefinitions = null;
		if (processLocations != null) {
			processdefinitions = processLocations.getFile();
		} else {
			// 没有注入流程定义文件夹地址则默认取classpath下的processes文件夹
			URL url = getClass().getClassLoader().getResource("processes");
			processdefinitions = new File(url.getFile());
		}
		ObjectFactory objectFactory = new DefaultObjectFactory(new SpringBeanCreator(beanFactory));
		// 没有注入processFactory则使用默认的XML方式的流程定义工厂
		processFactory = new XMLProcessFactory(objectFactory, processdefinitions);
	}

}
